﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RIS.TMP.WEB.APP.AddMigrations;
using RIS.TMP.WEB.APP.Models;
using System.Web.Security;

namespace RIS.TMP.WEB.APP.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {

                return View();
           
        }

        [HttpGet]
        public ActionResult Login()
        {
            return View();
        }
         [HttpPost]
        [ValidateAntiForgeryToken]       
        public ActionResult Login(UserLogin u)
        {           
            
            if (ModelState.IsValid)
            {
                using (AllContext dc = new AllContext())
                {
                    var v = dc.UserLogins.Where(a => a.User.Equals(u.User) && a.Password.Equals(u.Password)).FirstOrDefault();
                    
                    if (v != null)
                    {
                        var Emp = dc.CFEmployees.Where(x => x.EmId.Equals(v.EmId)).FirstOrDefault();
                        Session["LogedUserID"] = v.IdLogin.ToString();
                        Session["LogedId"] = v.EmId.ToString();
                        Session["PermissionGrop"] = Emp.CFGroupPM.GPMId;
                        return RedirectToAction("Index");
                    }
                    else if (dc.UserLogins.Where(a => a.User.Equals(u.User)).FirstOrDefault() != null)
                    {
                        ModelState.AddModelError("", "Password ไม่ถูกต้อง");
                    }
                    else if (dc.UserLogins.Where(a => a.Password.Equals(u.Password)).FirstOrDefault() != null)
                    {
                        ModelState.AddModelError("", "Username ไม่ถูกต้อง");
                    }
                    else
                    {
                        ModelState.AddModelError("", "Username และ Password ไม่ถูกต้อง");
                    }
                }

            }
            return View(u);
        }
 
 
        public ActionResult AfterLogin()
        {
            if (Session["LogedUserID"] != null)
            {
                return View();
            }
            else
            {
                return RedirectToAction("Login", "Home");
            }
        }
    }
}
